package com.hmall.common.interceptor;

import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头中的user-info
        String userInfo = request.getHeader("user-info");
        //2、如果有值的话,设置到线程副本ThreadLocal中
        if (userInfo != null) {
            UserContext.setUser(Long.parseLong(userInfo));
        }
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //1、请求完成后清除ThreadLocal中的信息
        UserContext.removeUser();
    }
}
